<template>
  <div>
    <top-nav-bar :applyPageRoute="printtitle" @back="back"></top-nav-bar>
    <a-card :bordered="false" style="margin-top: 15px">
      <div class="basic__title">基本信息</div>
      <a-form-model ref="form" v-bind="layout" :model="form">
        <a-form-model-item>
          <template slot="label">
            <span class="redxing">*</span>
            {{ basicInfoName }}
          </template>
          <a-input v-model="form.name" :placeholder="placeholder" style="width: 240px" :maxLength="40" />
        </a-form-model-item>
        <a-form-model-item>
          <template slot="label">
            <span class="redxing">*</span>
            {{ basicInfoCoverName }}
          </template>
          <!-- <uploadImg @imgUrl1="coverUrl" @remove="removeCoverImg" :defaultImg="defaultImg" v-if="defaultImg"/>
          <uploadImg @imgUrl1="coverUrl" @remove="removeCoverImg" v-else/> -->
          <a-upload :show-upload-list="false" :before-upload="coverBeforeUpload">
            <div
              style="
                width: 80px;
                height: 80px;
                border: 1px dashed #e8e8e8;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <a-icon type="plus" v-if="!form.imgUrl" />
              <img :src="form.imgUrl" alt="" v-else style="width: 100%; height: 100%" />
            </div>
          </a-upload>
          <div style="color: #ccc" v-if="isShwoTextarea">建议上传正方形图片</div>
        </a-form-model-item>
        <a-form-model-item v-if="isShwoTextarea">
          <template slot="label">
            <span class="redxing">*</span>
            {{ basicBriefintroduction }}
          </template>
          <a-textarea
            :placeholder="textareaPlaceholder"
            :rows="3"
            :maxLength="30"
            style="width: 300px"
            v-model="form.introduction"
          />
        </a-form-model-item>
      </a-form-model>
      <div class="detail">
        <div class="detail__title">{{ infoText }}</div>
        <div class="detail__institution">
          <div style="width: 80px; height: 80px; display: none">
            <a-upload :beforeUpload="beforeUpload" class="upload-list-inline" :showUploadList="false">
              <div id="editonload">
                <a-icon type="picture" style="font-size: 20px" />
              </div>
            </a-upload>
            <div style="text-align: center; font-size: 14px; color: #666">添加图片</div>
          </div>
          <quill-editor v-model="form.content" ref="QuillEditor" :options="editorOption" style="height: 200px" />
        </div>
      </div>
    </a-card>
    <div class="page-footer">
      <a-button style="margin-right: 10px" @click="back">取消</a-button>
      <a-button type="primary" @click="save"> 保存 </a-button>
    </div>
  </div>
</template>

<script>
import topNavBar from '@/components/topNavBar/topNavBar'
import uploadImg from '@/components/uploadImg'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { uploadPic, createInfo, getCreateInfo, updateInfo } from '@/api/websiteCreate'
export default {
  components: { topNavBar, uploadImg, quillEditor },
  data() {
    return {
      printtitle: '',
      placeholder: '',
      basicInfoName: '',
      basicInfoCoverName: '',
      basicBriefintroduction: '',
      textareaPlaceholder: '',
      infoText: '',
      type: 1,
      layout: {
        labelCol: { span: 2 },
        wrapperCol: { span: 20 },
      },
      form: {
        name: '',
        imgUrl: '',
        introduction: '',
        content: '',
      },
      editorOption: {
        placeholder: '请输入',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              // [{ size: ['small', false, 'large', 'huge'] }],
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ color: [] }, { background: [] }],
              ['image', 'video'],
            ],
            handlers: {
              image: (value) => {
                if (value) {
                  console.log(456)
                  // document.querySelector('.upload-list-inline').click()
                  document.getElementById('editonload').click()
                } else {
                  //   this.quill.format('image', false)
                  this.$message.error('上传发生未知错误!')
                }
              },
              video: (value) => {
                if (value) {
                  document.getElementById('editonload').click()
                } else {
                  this.$message.error('上传发生未知错误!')
                }
              },
            },
          },
        },
      },
      isShwoTextarea: true,
    }
  },
  created() {
    this.handleText()
    if (this.$route.query.id) {
      getCreateInfo(this.$route.query.id)
        .then((res) => {
          this.form.name = res.name
          this.form.imgUrl = res.cover_image
          this.form.introduction = res.intro
          if (res.details) {
            this.form.content = res.details
          }
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
    }
  },
  methods: {
    handleText() {
      //热门课程
      //添加
      if (this.$route.query.tab == 2 && this.$route.query.type == 'create') {
        this.printtitle = '添加热门课程'
      }

      //编辑
      if (this.$route.query.tab == 2 && this.$route.query.type == 'edit') {
        this.printtitle = '编辑热门课程'
      }
      if (this.$route.query.tab == 2) {
        this.basicInfoName = '课程名称'
        this.placeholder = '请输入课程名称'
        this.basicInfoCoverName = '课程封面'
        this.basicBriefintroduction = '课程简介'
        this.textareaPlaceholder =
          '请填写课程简介，例如：针对4~8岁的孩子，重点培养的基础绘画技能、激发艺术表现。30字以内'
        this.infoText = '课程详情'
        this.type = 1
      }
      //名师
      if (this.$route.query.tab == 3 && this.$route.query.type == 'create') {
        this.printtitle = '添加名师'
      }
      if (this.$route.query.tab == 3 && this.$route.query.type == 'edit') {
        this.printtitle = '编辑名师'
      }
      if (this.$route.query.tab == 3) {
        this.basicInfoName = '老师姓名'
        this.placeholder = '请输入老师姓名'
        this.basicInfoCoverName = '老师照片'
        this.basicBriefintroduction = '老师简介'
        this.textareaPlaceholder = `请填写老师亮点，简短精炼，例如：5年教龄，名校毕业，平易近人。30字以内`
        this.infoText = '老师详情'
        this.type = 2
      }
      //明星学员
      if (this.$route.query.tab == 4 && this.$route.query.type == 'create') {
        this.printtitle = '添加明星学员'
      }
      if (this.$route.query.tab == 4 && this.$route.query.type == 'edit') {
        this.printtitle = '编辑明星学员'
      }
      if (this.$route.query.tab == 4) {
        this.basicInfoName = '学员姓名'
        this.placeholder = '请输入学员姓名'
        this.basicInfoCoverName = '学员照片'
        this.basicBriefintroduction = '学员简介'
        this.textareaPlaceholder = `请填写学员简介/宣言，例如： 持之以恒，必将有好的收获。闪亮之星小阮的学习之旅~。30字以内`
        this.infoText = '学员详情'
        this.type = 3
      }
      //活动
      if (this.$route.query.tab == 6 && this.$route.query.type == 'create') {
        this.printtitle = '添加活动风采'
      }
      if (this.$route.query.tab == 6 && this.$route.query.type == 'edit') {
        this.printtitle = '编辑活动风采'
      }
      if (this.$route.query.tab == 6) {
        this.basicInfoName = '活动名称'
        this.placeholder = '请输入活动名称'
        this.basicInfoCoverName = '活动封面'
        this.infoText = '活动详情'
        this.type = 4
        this.isShwoTextarea = false
      }
      //学习资料
      if (this.$route.query.tab == 7 && this.$route.query.type == 'create') {
        this.printtitle = '添加学习资料'
      }
      if (this.$route.query.tab == 7 && this.$route.query.type == 'edit') {
        this.printtitle = '编辑学习资料'
      }
      if (this.$route.query.tab == 7) {
        this.basicInfoName = '资料名称'
        this.placeholder = '请输入资料名称'
        this.basicInfoCoverName = '资料封面'
        this.infoText = '资料详情'
        this.type = 5
        this.isShwoTextarea = false
      }
      //新闻动态
      if (this.$route.query.tab == 8 && this.$route.query.type == 'create') {
        this.printtitle = '添加新闻动态'
      }
      if (this.$route.query.tab == 8 && this.$route.query.type == 'edit') {
        this.printtitle = '编辑新闻动态'
      }
      if (this.$route.query.tab == 8) {
        this.basicInfoName = '新闻标题'
        this.placeholder = '请输入新闻标题'
        this.basicInfoCoverName = '新闻封面'
        this.infoText = '新闻详情'
        this.type = 6
        this.isShwoTextarea = false
      }
    },
    coverBeforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/svg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      if (!isJpgOrPng) {
        this.$message.error('只能上传图片格式！')
        return
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('只能上传10MB以内的图片!')
        return
      }
      const formData = new FormData()
      formData.append('file', file)
      formData.append('school_id', this.$store.state.user.school)
      uploadPic(formData)
        .then((res) => {
          this.form.imgUrl = res.url
          this.form.path = res.path
        })
        .catch((err) => {
          this.$message.error(err.data.message || '上传失败')
        })
      return false
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/svg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif' ||
        file.type === 'video/ogg' ||
        file.type === 'video/flv' ||
        file.type === 'video/avi' ||
        file.type === 'video/wmv' ||
        file.type === 'video/mov' ||
        file.type === 'video/mp4'
      if (!isJpgOrPng) {
        this.$message.error('只能上传图片/视频！')
        return
      }
      const formData = new FormData()
      formData.append('file', file)
      formData.append('school_id', this.$store.state.user.school)
      let quill = this.$refs.QuillEditor.quill
      uploadPic(formData).then((res) => {
        let length = quill.getSelection().index
        if (
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/svg' ||
          file.type === 'image/jpg' ||
          file.type === 'image/gif'
        ) {
          quill.insertEmbed(length, 'image', res.url)
        } else {
          quill.insertEmbed(length, 'video', res.url)
        }
        quill.setSelection(length + 1)
      })
      return false
    },
    save() {
      let parmars = JSON.parse(JSON.stringify(this.form))
      if (parmars.name == '') {
        this.$message.warning(this.basicInfoName + '不能为空!')
        return
      }
      if (parmars.imgUrl == '') {
        this.$message.warning(this.basicInfoCoverName + '不能为空!')
        return
      }
      if (this.isShwoTextarea) {
        if (parmars.introduction == '') {
          this.$message.warning(this.basicBriefintroduction + '不能为空!')
          return
        }
      }
      if (this.$route.query.id) {
        // let url='https://dev.earfox.cn/uploads/images/1/2021/02/01/49ef5e70425580ef2c433129ee7490d6.jpg'
        var domain = parmars.imgUrl.split('images/'); //以“/”进行分割
        parmars.path='images/'+domain[1]
      }
      let data = {
        details: {},
      }
      data.school_id = this.$store.state.user.school
      data.name = parmars.name
      data.type = this.type
      let obj = {}
      obj.url = parmars.imgUrl
      obj.path = parmars.path

      data.cover_image = obj
      if (this.isShwoTextarea) {
        data.intro = parmars.introduction
      }
      data.details = parmars.content
      if (!this.$route.query.id) {
        createInfo(data)
          .then((res) => {
            this.$message.success('保存成功')
            this.back()
          })
          .catch((err) => {
            this.$message.error(err.data.message || '保存失败')
          })
      }
      if (this.$route.query.id) {
        updateInfo(data, this.$route.query.id)
          .then((res) => {
            this.$message.success('编辑成功')
            this.back()
          })
          .catch((err) => {
            this.$message.error(err.data.message || '编辑失败')
          })
      }
    },
    back() {
      this.$router.push({
        name: 'websiteOrganizationInfo',
        query: {
          selRadio: this.$route.query.tab,
        },
      })
    },
  },
}
</script>
<style >
.ant-upload.ant-upload-select-picture-card {
  width: 80px !important;
  height: 80px !important;
}
</style>
<style lang="less" scoped>
.basic__title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}
.redxing {
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
}
.detail {
  margin-top: 32px;
  .detail__title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 20px;
  }
  .detail__institution {
    padding-left: 44px;
    padding-bottom: 44px;
    width: 500px;
  }
}
.page-footer {
  position: fixed;
  bottom: 0;
  left: 0px;
  width: 100%;
  height: 48px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 72px;
  border-top: 1px solid #e8e8e8;
}
</style>